﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using JetBrains.Annotations;
using Missbot.AIModule.Base;
using Missbot.Core.Base;
using Missbot.Core.SyntaxChecker.ParamCheckers;

namespace Missbot.AIModule.Repeator
{
    [UsedImplicitly]
    public class PlusOneMod : IAIModule
    {
        public override string Name => "+1复读";
        public override AIPriority Priority => AIPriority.Low;

        private List<PlusOneModel> CacheList { get; } = new();

        protected override bool OnInboxImpl(InboxSession session)
        {
            if (base.OnInboxImpl(session))
            {
                return true;
            }

            if (session.Group == null || session.Channel.BindingType != ChannelType.Messaging || string.IsNullOrEmpty(session.Text))
            {
                return false;
            }

            var checker = new UserParam();
            var checkResult = checker.Check(session.Text);
            if (checkResult.isValid)
            {
                return false;
            }

            var query = CacheList.FirstOrDefault(d => d.GroupID == session.Group.ID);
            if (query == null)
            {
                CacheList.Add(new PlusOneModel { GroupID = session.Group.ID, IsAlreadyRepeated = false, MsgCache = session.User.ID });
                return false;
            }

            Thread.Sleep(2000);
            Repeat(session, query);
            return true;
        }

        /// <summary>
        /// 复读
        /// </summary>
        /// <param name="session"></param>
        /// <param name="groupCache"></param>
        private void Repeat(InboxSession session, PlusOneModel groupCache)
        {
            if (groupCache.MsgCache != session.Text)
            {
                groupCache.MsgCache = session.Text;
                groupCache.IsAlreadyRepeated = false;

                return;
            }

            if (groupCache.IsAlreadyRepeated)
            {
                return;
            }

            session.SendBack(session.Text);
            groupCache.IsAlreadyRepeated = true;
        }
    }
}